package com.ymatou.iapi.sellerquery.testcase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.query.seller.trading.api.parameter.GetLastestPaidOrdersBean;
import com.ymatou.query.trading.api.parameter.GetLatestPaidOrdersResponse;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.database.sqlwapper.YmtOrdersWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 获取最近支付成功的订单信息 FreeMaker Template自动生成代码
 * 接口已经转接java
 */
@TestSuite
public class Ts_GetLatestPaidOrders {
	private static GetLastestPaidOrdersBean getlastestpaidordersBean;
//	private static com.ymatou.query.seller.trading.api.service.GetLastestPaidOrdersCall getlastestpaidordersCall;
	private static com.ymatou.iapi.trading.sellerquery.service.GetLastestPaidOrdersCall getlastestpaidordersCall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("获取最近支付成功的订单信息");
	}

	@Before
	public void caseUp() {
		getlastestpaidordersBean = new GetLastestPaidOrdersBean();
//		getlastestpaidordersCall = new com.ymatou.query.seller.trading.api.service.GetLastestPaidOrdersCall();
		getlastestpaidordersCall = new com.ymatou.iapi.trading.sellerquery.service.GetLastestPaidOrdersCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getlastestpaidordersCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verify() {
		GetLatestPaidOrdersResponse expectedResponse = new GetLatestPaidOrdersResponse();
		ConstructExpectedResponse(expectedResponse);
		List<GetLatestPaidOrdersResponse.OrderInfo> expected200Orders = orders;
		GetLatestPaidOrdersResponse actualResponse = getlastestpaidordersCall
				.getLatestPaidOrdersResponse();
		if (expected200Orders.size() >= getlastestpaidordersBean.getPageSize()) {
			DataUtil.verifyEquals(getlastestpaidordersBean.getPageSize(),
					actualResponse.getOrders().size(), "验证Orders的数量");
		} else {
			DataUtil.verifyEquals(expected200Orders.size(), actualResponse
					.getOrders().size(), "验证Orders的数量");
		}
		for (GetLatestPaidOrdersResponse.OrderInfo actual : actualResponse
				.getOrders()) {
			boolean exists = expected200Orders.stream().anyMatch(
					x -> x.getOrderId() == actual.getOrderId());
			DataUtil.verifyEquals(true, exists,
					"验证OrderId:" + actual.getOrderId() + "是否应该存在");
			if (exists) {
				GetLatestPaidOrdersResponse.OrderInfo expect = expected200Orders
						.stream()
						.filter(x -> x.getOrderId() == actual.getOrderId())
						.collect(Collectors.toList()).get(0);
				DataUtil.verifyEquals(expect.getBuyerId(), actual.getBuyerId(),
						"验证OrderId：" + actual.getOrderId() + "的BuyerId");
				DataUtil.verifyDateEquals(expect.getCreatedTime(),
						actual.getCreatedTime(),
						"验证OrderId：" + actual.getOrderId() + "的CreatedTime");
				DataUtil.verifyEquals(expect.getProductId(),
						actual.getProductId(),
						"验证OrderId：" + actual.getOrderId() + "的ProductId");
				DataUtil.verifyEquals(expect.getProductName(),
						actual.getProductName(),
						"验证OrderId：" + actual.getOrderId() + "的ProductName");
				DataUtil.verifyEquals(expect.getProductPicUrl(),
						actual.getProductPicUrl(),
						"验证OrderId：" + actual.getOrderId() + "的ProductPicUrl");
				DataUtil.verifyEquals(expect.getSellerId(),
						actual.getSellerId(),
						"验证OrderId：" + actual.getOrderId() + "的SellerId");
			}
		}
	}

	private void ConstructExpectedResponse(GetLatestPaidOrdersResponse response) {
		if (NeedSync()) {
			Sync();
		}
		// List<GetLatestPaidOrdersResponse.OrderInfo> orders =
		// RandomFetchOrders(getlastestpaidordersBean.getPageSize());
		// response.setOrders(orders);
	}

	private static List<GetLatestPaidOrdersResponse.OrderInfo> orders = new ArrayList<GetLatestPaidOrdersResponse.OrderInfo>();
	private static String lastSyncTime;

	private static boolean NeedSync() {
		return lastSyncTime == null
				|| YMTDateUtil
						.diffMinute(YMTDateUtil.getDate(), YMTDateUtil
								.parseDate(lastSyncTime, YMTDateUtil.YMDHMS)) > 1;
	}

	@SuppressWarnings("rawtypes")
	private void Sync() {
		YmtOrdersWapper ymtOrdersWapper = new YmtOrdersWapper();
		String queryField = "top 200 o.iOrderId as orderId";
		queryField += ",o.iUserId as buyerId";
		queryField += ",o.iBuyerId as sellerId";
		queryField += ",o.bShangouOrder as shangou";
		queryField += ",o.dAddTime as createdTime";
		queryField += ",i.sTitle as productName";
		queryField += ",i.sProductId as productId";
		queryField += ",i.sPictureUrl as productPicUrl";
		String joinCondition = " cross apply (select top 1 sTitle,sProductId,sPictureUrl from ymt_orderinfo(nolock) i where iorderid = o.iorderid) i";
		String queryCondition = " dPaidTime is not null order by o.dPaidTime desc";
		List<Map> results = ymtOrdersWapper.selectOrders2(queryField,
				joinCondition, queryCondition);
		if (DataUtil.isNullOrEmpty(results) == false) {
			for (Map m : results) {
				GetLatestPaidOrdersResponse.OrderInfo o = new GetLatestPaidOrdersResponse.OrderInfo();
				DataUtil.mapToBean(o, m);
				orders.add(o);
			}
		}
		lastSyncTime = YMTDateUtil.getSysTime();
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetLastestPaidOrders_001() {
		Logger.start(true, "获取最近支付成功的订单信息,10条记录");
		try {
			Logger.comment("准备前置数据");
			// OrderCreate c = new OrderCreate();
			// int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			// int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			// c.create2_PayOrder(userId, sellerId);
			// c.create1_BatchC2COrder(userId, sellerId, 1);
			// c.create1_M2cOrder(userId, sellerId);
			// c.create4_ReceivedOrder(userId, sellerId);
			// c.create4_RefundOrder(userId, sellerId);
			// c.create101_WaitPostPayOrder(userId, sellerId);
			// c.create12_UserCancelOrder(userId, sellerId);
			// c.create13_SellerCancelOrder(userId, sellerId);
			// c.create17_AcceptOrder(userId, sellerId);
			Logger.comment("准备前置数据结束");
			getlastestpaidordersBean.setPageSize(10);
			String param = FormatUtil.beanToHttpString(
					getlastestpaidordersBean, true, false);
			getlastestpaidordersCall.setData(param);
			getlastestpaidordersCall.callService();
			// Logger.comment("getlastestpaidordersCall send:" +
			// getlastestpaidordersCall.getEntityString());
			// Logger.comment("getlastestpaidordersCall response:" +
			// getlastestpaidordersCall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS,
					getlastestpaidordersCall.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetLastestPaidOrders_002() {
		Logger.start(true, "PageSize为0");
		try {
			getlastestpaidordersBean.setPageSize(0);
			String param = FormatUtil.beanToHttpString(
					getlastestpaidordersBean, true, false);
			getlastestpaidordersCall.setData(param);
			getlastestpaidordersCall.callService();
			Logger.comment("getlastestpaidordersCall send:"
					+ getlastestpaidordersCall.getEntityString());
			Logger.comment("getlastestpaidordersCall response:"
					+ getlastestpaidordersCall.getReturnData());
			Logger.verifyEquals(ECode.ERROR400,
					getlastestpaidordersCall.getCode(), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetLastestPaidOrders_003() {
		Logger.start(true, "PageSize大于200");
		try {
			getlastestpaidordersBean.setPageSize(201);
			String param = FormatUtil.beanToHttpString(
					getlastestpaidordersBean, true, false);
			getlastestpaidordersCall.setData(param);
			getlastestpaidordersCall.callService();
			// Logger.comment("getlastestpaidordersCall send:" +
			// getlastestpaidordersCall.getEntityString());
			// Logger.comment("getlastestpaidordersCall response:" +
			// getlastestpaidordersCall.getReturnData());
			Logger.verifyEquals(ECode.ERROR400,
					getlastestpaidordersCall.getCode(), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetLastestPaidOrders_004() {
		Logger.start(true, "PageSize为null");
		try {
			getlastestpaidordersBean.setPageSize(null);
			String param = FormatUtil.beanToHttpString(
					getlastestpaidordersBean, true, false);
			getlastestpaidordersCall.setData(param);
			getlastestpaidordersCall.callService();
			Logger.comment("getlastestpaidordersCall send:"
					+ getlastestpaidordersCall.getEntityString());
			Logger.comment("getlastestpaidordersCall response:"
					+ getlastestpaidordersCall.getReturnData());
			Logger.verifyEquals(ECode.ERROR400,
					getlastestpaidordersCall.getCode(), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetLastestPaidOrders_005() {
		Logger.start(true, "获取最近支付成功的订单信息,20条记录");
		try {
			getlastestpaidordersBean.setPageSize(20);
			String param = FormatUtil.beanToHttpString(
					getlastestpaidordersBean, true, false);
			getlastestpaidordersCall.setData(param);
			getlastestpaidordersCall.callService();
			Logger.comment("getlastestpaidordersCall send:"
					+ getlastestpaidordersCall.getEntityString());
			Logger.comment("getlastestpaidordersCall response:"
					+ getlastestpaidordersCall.getReturnData());
			Logger.verifyEquals(ECode.SUCCESS,
					getlastestpaidordersCall.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}